﻿/// SDMX Artefact TUtilities. A component for SDMX SAE Tools.
///    Copyright (C) 2011  Philippe Prati 
///
///    This program is free software: you can redistribute it and/or modify
///    it under the terms of the GNU General Public License as published by
///    the Free Software Foundation, either version 2 of the License, or
///    (at your option) any later version.
///
///    This program is distributed in the hope that it will be useful,
///    but WITHOUT ANY WARRANTY; without even the implied warranty of
///    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
///    GNU General Public License for more details.
///
///    You should have received a copy of the GNU General Public License
///    along with this program.  If not, see <http://www.gnu.org/licenses/>.
///
///    Contact: ph.prati@bluewin.ch         www.sdmx.ch
///    
using System;
using System.Data;
using System.Web;
using System.Text;
using System.Web.Services;
using System.Xml;
using System.Configuration;
using SdmxMl.Multiplexor;
using SdmxMl.Manager;
using SdmxMl.Common;
using SdmxMl.Structure;

namespace SdmxUtil
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://www.sdmx.ch/SAE/Util")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ArtefactUtility : System.Web.Services.WebService
    {
        #region Test Method (Version)

        [WebMethod(Description = "Test allows to retrieve service version")]
        public XmlElement Test()
        {
            
            string title = "SDMX SAE Tool component: Artefact utilities";
            StatusMessage status = new StatusMessage(StatusType.Success, title + " version: " +
                System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
            return status.Element;
        }

        #endregion

        #region Update Finalized

        [WebMethod(Description = "Submits text modification of a finalized artefact." +
            " NOTE: FullId = 'AgencyId+Id+Version'")]
        public XmlElement UpdateFinalized(string user, string pwd, string artType, string fullId, XmlElement elArtefact)
        {
            StatusMessage status = new StatusMessage(StatusType.Failure, "Request interrupted");
            bool isCheckOut = false;
            RegProxy reg = null;
            RegistryMultiplex multiplexor = null;
            string adminUser = string.Empty;
            try
            {
                multiplexor = new RegistryMultiplex();

                if (ConfigurationSettings.AppSettings["FullAdministrator"] == null ||
                    ConfigurationSettings.AppSettings["FullAdministrator"].ToString().Trim() == string.Empty)
                    throw new ApplicationException("Unknown administrative properties defined");
                
                adminUser = ConfigurationSettings.AppSettings["FullAdministrator"].ToString().Trim();

                multiplexor.UserId = adminUser;

                reg = multiplexor.GetProxyForGroup(fullId);

                // Fetch artefact with updated texts
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(elArtefact.OuterXml);

                // Version 1.6 of service required
                if (reg.Version < 1.6)
                    throw new ApplicationException("Registry Version 1.6 or more required.");

                if (reg.IsOwner(user, fullId))
                {
                    status = new StatusMessage(StatusType.Success, null);
                    reg.CheckOut(artType, fullId);
                    isCheckOut = true;

                    XmlDocument xDocFinal = reg.GetArtefact(artType, fullId);

                    ArtefactTextUpdater textUpdater = new ArtefactTextUpdater(xDocFinal, xDoc, fullId);
                    xDoc = textUpdater.Update();
                    if (xDoc == null)
                        throw new ApplicationException("Requires a finalized artefact in Registry.");
                    else
                        reg.SubmitArtefact(artType, fullId, xDoc.DocumentElement);
                }
                else
                    throw new ApplicationException("The user " + user + " is not owner of the artefact " + fullId);

            }
            catch (Exception ex)
            {
                if (ex is ApplicationException)
                    status = new StatusMessage(StatusType.Failure, ex.Message);
                else
                    status = new StatusMessage(StatusType.Failure, "Unable to register Artefact " + fullId);

                if (isCheckOut)
                {
                    try
                    {
                        multiplexor = new RegistryMultiplex();
                        multiplexor.UserId = adminUser;
                        reg = multiplexor.GetProxyForGroup(fullId);
                        reg.UndoCheckOut(artType, fullId);
                    }
                    catch { }
                }

            }

            return status.Element;
        }
        

        #endregion

    }
}
